﻿using SingleBlog.Core;
using System;
using System.Security.Claims;
using System.Security.Principal;

namespace SingleBlog
{
    /// <summary>
    /// 表示对 <see cref="Microsoft.AspNetCore.Identity"/> 的扩展实例。
    /// </summary>
    public static class IdentityExtension
    {
        /// <summary>
        /// 获取当前授权用户的 UserId 字段。
        /// </summary>
        /// <param name="identity"><see cref="IIdentity"/> 实例。</param>
        /// <returns></returns>
        public static int UserId(this IIdentity identity)
        => identity.Get<int>(ClaimTypes.NameIdentifier);

        /// <summary>
        /// 获取指定的声明类型。
        /// </summary>
        /// <typeparam name="T">一种数据类型。</typeparam>
        /// <param name="identity"><see cref="IIdentity"/> 实例。</param>
        /// <param name="claimType">一种声明的类型。可从 <see cref="ClaimTypes"/> 类型中选择，或自定义的类型。</param>
        /// <returns></returns>
        public static T Get<T>(this IIdentity identity, string claimType)
        {
            var claimIdentity = (identity as ClaimsIdentity);
            if (claimIdentity == null)
            {
                return default(T);
            }

            var claim = claimIdentity.FindFirst(claimType);
            if (claim == null)
            {
                return default(T);
            }

            return claim.Value.To<T>();
        }

        /// <summary>
        /// 表示当前登录用户是否是管理员。未登录直接返回 <c>false</c>.
        /// </summary>
        /// <param name="principal">The principal.</param>
        /// <returns>
        ///   未登录状态或已登录但不是管理员都返回 <c>false</c>；否则返回 <c>true</c>。
        /// </returns>
        public static bool IsAdmin(this IPrincipal principal)
            => principal.Identity.IsAuthenticated && principal.IsInRole(Core.Data.SingleBlogRole.ADMINISTRATOR);
    }
}
